package dao

import (
	"encoding/json"
	"time"
)

type UserRedis struct{}

var UserCache UserRedis

const (
	namespace = "easyarch:UserCache"
)

func (r *UserRedis) AddUserCache(user *User) error {
	// 第三个参数代表key的过期时间，0代表不会过期。
	key := user.Username
	value, err := json.Marshal(user)
	if err != nil {
		return err
	}
	err = client.Set(namespace+key, value, time.Minute*30).Err()
	if err != nil {
		return err
	}
	return nil
}

func (r *UserRedis) DelUserCacheByUsername(user *User) error {
	key := user.Username
	return client.Del(namespace + key).Err()
}

func (r *UserRedis) GetUserCacheByUsername(user *User) (*User, error) {
	key := user.Username
	value, err := client.Get(namespace + key).Result()
	if err != nil {
		return nil, err
	}

	newUser := &User{}
	err = json.Unmarshal([]byte(value), newUser)
	if err != nil {
		return nil, err
	}
	return newUser, nil
}
